/*!
 * Jangle v1.0
 * Copyright 2011, Calvin Davis
 */
(function($) {
	$.fn.jangle = function(options) {
		
		var default_arcs = 8;
		var default_prefix = 'jangle-';	
		var settings = {
			arcs: default_arcs,
			prefix: default_prefix
		};
		if (options) {
			$.extend(settings, options);
		}
		
		// Make sure arcs is a usable number
		settings.arcs = Math.round(settings.arcs);
		if (settings.arcs < 1) {
			settings.arcs = default_arcs;
		}
		var arc = 360 / settings.arcs;
		
		// This regex will match any classes added by Jangle
		var reg = new RegExp('( *)' + settings.prefix + '[^ ]*', 'g');
		
		return this.each(function() {
			
			var t = $(this);
			
			$('html').bind('mousemove.jangle', function(e) {
				// Get target position and size
				var tx = t.offset().left;
				var ty = t.offset().top;
				var tw = t.outerWidth();
				var th = t.outerHeight();
				
				// Get mouse position
				var mx = e.pageX;
				var my = e.pageY;
				
				var c = settings.prefix;
				
				if (mx >= tx && mx < tx + tw && my >= ty && my < ty + th) {
					// Mouse is inside target
					c += 'c';
				} else {
					// Calculate angle between target centre and mouse	
					var dx = mx - (tx + tw / 2);
					var dy = my - (ty + th / 2);
					var rad = Math.atan2(dy, dx);
					var deg = (450 + arc / 2 + rad * 180 / Math.PI) % 360;
					
					// Calculate the number of the arc that the mouse is in
					var a = Math.floor(1 + deg / arc);
					c += a;
				}
				
				// Remove any Jangle classes from the target and add new class
				t[0].className = t[0].className.replace(reg, '');
				t.addClass(c);
			});
		});
	}
})(jQuery);